package com.diaohw.module.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.ArrayList;
import java.util.UUID;

import static com.diaohw.platform.common.constant.RequestConstant.LINK_ID;
import static com.diaohw.platform.common.constant.RequestConstant.REQUEST_ID;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;

/**
 * @author 刁海文
 * @Remark
 * @since 2023/7/6 20:16
 */
@Component
public class GatewayGlobalFilter implements GlobalFilter, Ordered {


    private final static String DEFAULT_FILTER_PATH = "/websocket/";

    private static String convertWsToHttp(String scheme) {
        scheme = scheme.toLowerCase();
        return "ws".equals(scheme) ? "http" : "wss".equals(scheme) ? "https" : scheme;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        URI requestUrl = exchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
        // 重写请求头并添加自定义header头
        ServerHttpRequest newRequest = exchange
                .getRequest()
                .mutate()
                // 为请求追加 Request ID 参数
                .header(REQUEST_ID, UUID.randomUUID().toString())
                // 为请求添加链路编号
                .header(LINK_ID, "1")
                .build();

        ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();

        String scheme = requestUrl.getScheme();
        if (!"ws".equals(scheme) && !"wss".equals(scheme)) {
            return chain.filter(newExchange);
        }
        if (requestUrl.getPath().startsWith(DEFAULT_FILTER_PATH)) {
            String wsScheme = convertWsToHttp(scheme);
            URI wsRequestUrl = UriComponentsBuilder.fromUri(requestUrl).scheme(wsScheme).build().toUri();
            newExchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, wsRequestUrl);
        }

        //解决返回多个origin信息
        return chain.filter(exchange).then(Mono.defer(() -> {
            exchange.getResponse().getHeaders().entrySet().stream()
                    .filter(kv -> (kv.getValue() != null && kv.getValue().size() > 1))
                    .filter(kv -> (kv.getKey().equals(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)
                            || kv.getKey().equals(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)))
                    .forEach(kv -> {
                        kv.setValue(new ArrayList<>() {{
                            add(kv.getValue().get(0));
                        }});
                    });

            return chain.filter(newExchange);
        }));
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE - 2;
    }
}
